package com.example.epidemic_assistant.ui.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.android.epidemic_assistant.gen.DaoSession;
import com.android.epidemic_assistant.gen.UserBeanDao;
import com.bumptech.glide.Glide;
import com.example.epidemic_assistant.App;
import com.example.epidemic_assistant.R;
import com.example.epidemic_assistant.bean.UserBean;
import com.example.epidemic_assistant.ui.LoginActivity;
import com.example.epidemic_assistant.util.GlideEngine;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_CANCELED;
import static android.content.Context.MODE_PRIVATE;

/**
 * 我的 - 碎片
 */
public class MyFragment extends Fragment {

    private static final String TAG = "MyFragment";

    private ImageView mImgPhoto;
    private TextView mTvName;
    private TextView mTvAge;
    private TextView mTvSex;
    private RelativeLayout mRatChangePass;
    private RelativeLayout mRatLogout;
    private RelativeLayout mRatOut;
    private RelativeLayout mRatMiantenance;
    private String mUsername;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;

    private App mMyApp;
    private DaoSession mDaoSession;
    private UserBeanDao mUserBeanDao;
    private UserBean mUserBean;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_my, container, false);

        initView(view);
        initData();
        initListener();

        return view;
    }

    private void initListener() {
        mRatChangePass.setOnClickListener(v -> {
            View view = LayoutInflater.from(requireContext()).inflate(R.layout.item_dialog_chage_password,null,false);
            EditText edtPass = view.findViewById(R.id.edt_pass);
            EditText edtSurePass = view.findViewById(R.id.edt_sure_pass);
            AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
            dialog.setTitle(requireContext().getString(R.string.change_pass));
            dialog.setView(view);
            dialog.setPositiveButton(requireContext().getString(R.string.sure), (dialog1, which) -> {
                String pass = edtPass.getText().toString().trim();
                String surePass = edtSurePass.getText().toString().trim();
                if (!pass.equals(surePass)) {
                    showToast("2次密码输入不一致，请重新输入!");
                } else if (pass.isEmpty() || surePass.isEmpty()){
                    showToast("密码不能为空!");
                } else {
                    mUserBean.setUserPass(pass);
                    mUserBeanDao.update(mUserBean);
                    showToast("修改成功!");
                    goLogin();
                }
            });
            dialog.setNegativeButton(requireContext().getString(R.string.cancel), null);
            dialog.create().show();
        });
        mRatLogout.setOnClickListener(v -> {
            AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
            dialog.setTitle(requireContext().getString(R.string.hint));
            dialog.setMessage(requireContext().getString(R.string.sure_logout));
            dialog.setPositiveButton(requireContext().getString(R.string.sure), (dialog1, which) -> {
                if (mUserBean.getDay() >= 14) {
                    mUserBean.setRoomId(100); //注销改为100
                    mUserBeanDao.update(mUserBean);
                    goLogin();
                }else {
                    showToast("隔离尚未结束，隔离结束才可注销!");
                }
            });
            dialog.setNegativeButton(requireContext().getString(R.string.cancel), null);
            dialog.create().show();
        });
        mRatOut.setOnClickListener(v -> {
            AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
            dialog.setTitle(requireContext().getString(R.string.hint));
            dialog.setMessage(requireContext().getString(R.string.sure_out));
            dialog.setPositiveButton(requireContext().getString(R.string.sure), (dialog1, which) -> {
                goLogin();
            });
            dialog.setNegativeButton(requireContext().getString(R.string.cancel), null);
            dialog.create().show();
        });
        mRatMiantenance.setOnClickListener(view -> {
            AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
            dialog.setTitle(requireContext().getString(R.string.hint));
            dialog.setMessage(requireContext().getString(R.string.sure_maintenance));
            dialog.setPositiveButton(requireContext().getString(R.string.report), (dialogInterface, i) -> {
                mUserBean.setIsMaintain(true);
                mUserBeanDao.update(mUserBean);
                showToast("上报成功，请耐心等待");
            });
            dialog.setNegativeButton(requireContext().getString(R.string.cancel), null);
            dialog.create().show();
        });
        mImgPhoto.setOnClickListener(view -> {
            EasyPhotos.createAlbum(MyFragment.this, true,false,
                    GlideEngine.getInstance()).setFileProviderAuthority("com.example" +
                    ".epidemic_assistant.fileprovider").start(0);
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (data != null) {
                ArrayList<Photo> photos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                if (photos != null) {
                    mUserBean.setUserPhoto(photos.get(0).path);
                    mUserBeanDao.update(mUserBean);
                    Glide.with(this).load(photos.get(0).uri).into(mImgPhoto);
                }
            }
        } else if (RESULT_CANCELED == resultCode) {
            Toast.makeText(requireContext(), getString(R.string.cancel), Toast.LENGTH_SHORT).show();
        }
    }

    private void initData() {
        mMyApp = (App) getActivity().getApplication();
        mDaoSession = mMyApp.getDaoSession();
        mUserBeanDao = mDaoSession.getUserBeanDao();

        mSharedPreferences = getActivity().getSharedPreferences("autoLogin", MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
        String username = mSharedPreferences.getString("username", "");
        Log.d(TAG, "username-->" + username);
        if (!username.isEmpty()) {
            mUsername = username;
        } else {
            mUsername = getActivity().getIntent().getExtras().getString("username");
        }
        List<UserBean> list = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserName.eq(mUsername)).list();
        for (UserBean userBean : list) {
            if (userBean.getUserName().equals(mUsername)) {
                if (userBean != null) {
                    mUserBean = userBean;
                    mTvName.setText(userBean.getName());
                    mTvAge.setText(userBean.getAge());
                    mTvSex.setText(userBean.getSex());
                }
            }
        }
        if (mUserBean != null) {
            String userPhoto = mUserBean.getUserPhoto();
            if (userPhoto == null) {
                mImgPhoto.setImageResource(R.drawable.icon_my_man);
            } else {
                Glide.with(this).load(userPhoto).into(mImgPhoto);
            }
        }
    }

    private void initView(View view) {
        mImgPhoto = view.findViewById(R.id.img_photo);
        mTvName = view.findViewById(R.id.tv_my_name);
        mTvAge = view.findViewById(R.id.tv_my_age);
        mTvSex = view.findViewById(R.id.tv_my_sex);
        mRatChangePass = view.findViewById(R.id.rat_changePass);
        mRatLogout = view.findViewById(R.id.rat_logout);
        mRatOut = view.findViewById(R.id.rat_out);
        mRatMiantenance = view.findViewById(R.id.rat_maintenance);
    }

    private void goLogin() {
        mEditor.putBoolean("autoLogin", false);
        mEditor.apply();
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
    }

    private void showToast(String msg) {
        Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show();
    }
}